﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Fortunate.Common.Helper
{
    public static class RandomCodeHelper
    {
        private static readonly string randomchars1 = "abcdefghijklmnpqrstuvwxyz";
        private static readonly string randomchars2 = "0123456789";
        private static readonly string randomchars3 = "ABCDEFGHIJKLMNPQRSTUVWXYZ";
        private static readonly string randomchars4 = "~!@#$%^&*()_+|";

        public static string GetRandomValidCode()
        {
            return MakePassword(randomchars2, 6);
        }
        public static string GetRandomPassword()
        {
            return
                MakePassword(randomchars3, 3) +
                MakePassword(randomchars4, 3) +
                MakePassword(randomchars2, 3) +
                MakePassword(randomchars1, 3) +
                MakePassword(randomchars3, 1) +
                MakePassword(randomchars4, 1) +
                MakePassword(randomchars2, 1) +
                MakePassword(randomchars1, 1);
        }
        public static string MakePassword(string pwdchars, int pwdlength)
        {
            string tmpstr = "";
            int iRandNum;
            if (pwdlength > pwdchars.Length)
            {
                throw new Exception("长度过长！" + pwdchars.Length);
            }
            Random rnd = new Random(getNewSeed());
            for (int i = 0; i < pwdlength; i++)
            {
                iRandNum = rnd.Next(pwdchars.Length);
                tmpstr += pwdchars[iRandNum];
            }
            return tmpstr;
        }
        /// <summary>
        /// 生成随机数的种子
        /// </summary>
        /// <returns></returns>
        private static int getNewSeed()
        {
            byte[] rndBytes = new byte[4];
            System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
            rng.GetBytes(rndBytes);
            return BitConverter.ToInt32(rndBytes, 0);
        }
    }
}
